package com.atwisdom.star.core.dsl.basics.Impl;

import com.alibaba.fastjson.JSONObject;
import com.atwisdom.star.common.actionType.basic.EventActionType;
import com.atwisdom.star.common.vo.*;
import com.atwisdom.star.core.dao.pojo.Event;
import com.atwisdom.star.core.dao.service.impl.EventServiceImpl;
import com.atwisdom.star.core.dsl.BaseDslService;
import com.atwisdom.star.core.dsl.basics.EventDslService;
import com.atwisdom.star.exception.pojo.BusinessException;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

@Component
@EnableAspectJAutoProxy(exposeProxy = true)
public class EventDslServiceImpl extends BaseDslService<Event> implements EventDslService {
    private EventServiceImpl eventService;

    @Autowired
    public void setEventService(EventServiceImpl eventService) {
        this.eventService = eventService;
    }

    @Transactional
    public ResultInfo<?> responseFactory(List<ActionData<JSONObject>> actionDataList) throws BusinessException {
        ResultInfo<?> resultInfo = null;
        for (ActionData<JSONObject> actionData : actionDataList) {
            String action = actionData.getAction();
            EventActionType actionType = EventActionType.valueOf(action);
            String methodName = actionType.getMethodName();
            resultInfo = this.execMethod(methodName, actionData);
        }
        return resultInfo;
    }

    /**
     * 反射执行业务方法
     *
     * @param methodName 方法名称
     * @param actionData 接收参数
     * @return 返回统一结果类型(ResultInfo)
     * @throws BusinessException 业务数据异常
     */
    public ResultInfo<?> execMethod(String methodName, ActionData<JSONObject> actionData) throws BusinessException {
        Class<? extends EventDslServiceImpl> clz = this.getClass();
        Method method;
        try {
            method = clz.getMethod(methodName, ActionData.class);
            return (ResultInfo<?>) method.invoke(this, actionData);
        }catch(NoSuchMethodException ex){
            throw new BusinessException("999999","没有找到该方法("+methodName+")",ex);
        } catch (IllegalAccessException ex) {
            throw new BusinessException("999999","没有访问该方法权限("+methodName+")",ex);
        } catch (InvocationTargetException ex) {
            Throwable targetException = ex.getTargetException();
            if(targetException instanceof  BusinessException){
                BusinessException bex =  (BusinessException)targetException;
                throw new BusinessException("999999",bex.getErrorMsg(),ex);
            }else{
                throw new BusinessException("999999","出错了请重试：("+methodName+")---"+ex.getMessage(),ex);
            }
        }
    }

    /**
     * 添加模型
     *
     * @param actionData 接收参数
     * @return 返回统一结果类型(ResultInfo)
     */
    @Transactional
    @Override
    public ResultInfo<?> add(ActionData<JSONObject> actionData) {
        List<JSONObject> dataList = actionData.getData();
        if(dataList!=null && dataList.size()>0){
            JSONObject jsonObject = dataList.get(0);
            Event event = new Event(jsonObject);
            boolean b =  eventService.save(event);
            if(b){
                JSONObject eventJsonObject = event.fetchJsonObject();
                return JsonResult.success(eventJsonObject);
            }else{
                return JsonResult.error(StatusCode.ERROR_ADD);
            }
        }else{
            return JsonResult.error(StatusCode.ERROR_ADD.getCode(),"没有要添加的数据，添加操作失败！");
        }
    }

    /**
     * 批量添加
     *
     * @param actionData 接收参数
     * @return 返回统一结果类型(ResultInfo)
     */
    @Transactional
    @Override
    public ResultInfo<?> batchAdd(ActionData<JSONObject> actionData) {
        List<Event> events = this.transformActionDataList(actionData);
        boolean b = eventService.saveBatch(events);
        List<JSONObject> jsonObjectList = new ArrayList<>();
        events.forEach(c-> jsonObjectList.add(c.fetchJsonObject()));
        if(b){
            return JsonResult.success(jsonObjectList);
        }else{
            return JsonResult.error(StatusCode.ERROR_ADD);
        }
    }

    /**
     * 更新
     *
     * @param actionData 接收参数
     * @return 返回统一结果类型(ResultInfo)
     */
    @Transactional
    @Override
    public ResultInfo<?> update(ActionData<JSONObject> actionData) {
        List<JSONObject> dataList = actionData.getData();
        if(dataList!=null && dataList.size()>0){
            Event event = new Event(dataList.get(0));
            boolean b = eventService.updateById(event);
            if(b){
                return JsonResult.success(event);
            }else{
                return JsonResult.error(StatusCode.ERROR_UPDATE);
            }
        }else{
            return JsonResult.error(StatusCode.ERROR_UPDATE.getCode(),"没有要更新的数据，更新操作失败！");
        }
    }

    public boolean updatePublished(Long id,Boolean published){
        Event event = eventService.getById(id);
        String category = event.getCategory();
        String name = event.getName();
        if(published !=null && published){
            UpdateWrapper<Event> updateWrapper = new UpdateWrapper<>();
            updateWrapper.eq(StringUtils.isNotBlank(category),"category",category);
            updateWrapper.eq(StringUtils.isNotBlank(name),"name",name);
            updateWrapper.ne("id",id);
            Event newEvent = new Event();
            newEvent.setPublished(false);
            return eventService.update(newEvent, updateWrapper);
        }else{
            return true;
        }
    }

    /**
     * 批量更新
     *
     * @param actionData 接收参数
     * @return 返回统一结果类型(ResultInfo)
     */
    @Transactional
    @Override
    public ResultInfo<?> batchUpdate(ActionData<JSONObject> actionData) {
        List<Event> events = transformActionDataList(actionData);
        boolean b = eventService.updateBatchById(events);
        List<JSONObject> jsonObjectList = new ArrayList<>();
        events.forEach(c-> jsonObjectList.add(c.fetchJsonObject()));
        if(b){
            return JsonResult.success(jsonObjectList);
        }else{
            return JsonResult.error(StatusCode.ERROR_UPDATE);
        }
    }

    /**
     * 删除
     *
     * @param actionData 接收参数
     * @return 返回统一结果类型(ResultInfo)
     */
    @Transactional
    @Override
    public ResultInfo<Integer> delete(ActionData<JSONObject> actionData) {
        return this.batchDelete(actionData);
    }

    /**
     * 批量删除
     *
     * @param actionData 接收参数
     * @return 返回统一结果类型(ResultInfo)
     */
    @Transactional
    @Override
    public ResultInfo<Integer> batchDelete(ActionData<JSONObject> actionData) {
        if(!this.validActionData(actionData)){
            return JsonResult.error(StatusCode.ERROR_INVALID_DELETE);
        }
        QueryWrapper<Event> queryWrapper = this.buildQueryWrapper(actionData,false);
        int delCount = eventService.getBaseMapper().delete(queryWrapper);
        if(delCount >= 1){
            return JsonResult.success(delCount);
        }else{
            return JsonResult.error(StatusCode.ERROR_DELETE);
        }
    }

    /**
     * 根据id数组进行删除
     * @param actionData 参数
     * @return 返回结果
     */
    @Override
    public ResultInfo<Integer> deleteByIds(ActionData<JSONObject> actionData) {
        List<Long> ids = actionData.getIds();
        if(ids==null || ids.size() < 1){
            return JsonResult.error(StatusCode.ERROR_INVALID_DELETE);
        }
        int delCount =eventService.getBaseMapper().deleteBatchIds(ids);
        if(delCount >= 1){
            return JsonResult.success(delCount);
        } else {
            return JsonResult.error(StatusCode.ERROR_DELETE);
        }
    }

    /**
     * 不分页查询
     *
     * @param actionData 接收参数
     * @return 返回统一结果类型(ResultInfo)
     */
    @Override
    public ResultInfo<?> query(ActionData<JSONObject> actionData) {
           QueryWrapper<Event> helpQueryWrapper = this.buildQueryWrapper(actionData,false);
        this.buildOrderBy(helpQueryWrapper, actionData.getOrderBy(),"updateTime");
        List<Event> events = eventService.list(helpQueryWrapper);
        List<JSONObject> jsonObjectList = new ArrayList<>();
        events.forEach(c-> jsonObjectList.add(c.fetchJsonObject()));
        return  JsonResult.success(jsonObjectList);
    }

    /**
     * 根据类型和名称获取事件
     * @param category 类型
     * @param name 名称
     * @return 返回结果
     */
    public Event getEventBy(String category, String name) {
        QueryWrapper<Event> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("category", category);
        queryWrapper.eq("name", name);
        Event event = eventService.getBaseMapper().selectOne(queryWrapper);
        if (event == null) {
            throw new BusinessException("999999", "未查到数据");
        }
        return event;
    }

    /**
     * 不分页查询
     *
     * @param actionData 接收参数
     * @return 返回统一结果类型(ResultInfo)
     */
    @Override
    public ResultInfo<?> queryIncludeUnpublished(ActionData<JSONObject> actionData) {
        return this.queryByHasPublished(actionData,false);
    }

    /**
     * 不分页查询
     *
     * @param actionData 接收参数
     * @return 返回统一结果类型(ResultInfo)
     */
    private ResultInfo<?> queryByHasPublished(ActionData<JSONObject> actionData,boolean hasPublished) {
        QueryWrapper<Event> queryWrapper = new QueryWrapper<>();
        if(actionData!=null){
            queryWrapper = this.buildQueryWrapper(actionData,hasPublished);
        }
        List<Event> events = eventService.list(queryWrapper);
        List<JSONObject> jsonObjectList = new ArrayList<>();
        events.forEach(c-> jsonObjectList.add(c.fetchJsonObject()));
        return  JsonResult.success(jsonObjectList);
    }

    /**
     * 不分页查询
     * @param actionData  接收参数
     * @return 返回统一结果类型(ResultInfo )
     */
    @Override
    public ResultInfo<?> queryInfo(ActionData<JSONObject> actionData) {
        return  this.queryInfoByHasPublished(actionData,true);
    }

    /**
     * 不分页查询
     * @param actionData  接收参数
     * @return 返回统一结果类型(ResultInfo )
     */
    @Override
    public ResultInfo<?> queryInfoIncludeUnpublished(ActionData<JSONObject> actionData) {
        return  this.queryInfoByHasPublished(actionData,false);
    }

    /**
     * 不分页查询
     * @param actionData  接收参数
     * @return 返回统一结果类型(ResultInfo )
     */
    private ResultInfo<?> queryInfoByHasPublished(ActionData<JSONObject> actionData,boolean hasPublished) {
        QueryWrapper<Event> eventQueryWrapper = this.buildQueryWrapper(actionData,hasPublished);
        String[] needColumns = Event.fetchSimpleColumns();
        eventQueryWrapper.select(needColumns);
        List<Event> events = eventService.list(eventQueryWrapper);
        List<JSONObject> jsonObjectList = new ArrayList<>();
        events.forEach(c-> jsonObjectList.add(c.fetchJsonObject()));
        return  JsonResult.success(jsonObjectList);
    }

    /**
     * 根据id数组进行简单查询
     *
     * @param actionData 参数
     * @return 返回值
     */
    @Override
    public ResultInfo<?> queryByIds(ActionData<JSONObject> actionData) throws BusinessException {
        List<Long> ids = actionData.getIds();
        List<Event> events = eventService.listByIds(ids);
        List<JSONObject> jsonObjectList = new ArrayList<>();
        events.forEach(c-> jsonObjectList.add(c.fetchJsonObject()));
        return  JsonResult.success(jsonObjectList);
    }

    /**
     * 分页查询
     *
     * @param actionData 接收参数
     * @return 返回统一结果类型(ResultInfo)
     */
    @Override
    public ResultInfo<PageInfo> queryByPage(ActionData<JSONObject> actionData) {
        Page<Event> pageInfo = new Page<>(actionData.getPageNumber(), actionData.getPageSize());
        QueryWrapper<Event> eventQueryWrapper = this.buildQueryWrapper(actionData,false);
        this.buildOrderBy(eventQueryWrapper, actionData.getOrderBy(),"updateTime");
        return getPageInfoResult(pageInfo,eventQueryWrapper);
    }

    /**
     * 分页查询，去除复杂字段
     *
     * @param actionData 接收参数
     * @return 返回统一结果类型(ResultInfo)
     */
    @Override
    public ResultInfo<PageInfo> queryInfoByPage(ActionData<JSONObject> actionData) {
        Page<Event> pageInfo = new Page<>(actionData.getPageNumber(), actionData.getPageSize());
        QueryWrapper<Event> eventQueryWrapper = this.buildQueryWrapper(actionData);
        String[] needColumns = Event.fetchSimpleColumns();
        eventQueryWrapper.select(needColumns);
        return getPageInfoResult(pageInfo,eventQueryWrapper);
    }

    /**
     * 获取分页查询
     * @param pageInfo 参数
     * @param queryWrapper 参数
     * @return 返回结果
     */
    private ResultInfo<PageInfo> getPageInfoResult(Page<Event> pageInfo, QueryWrapper<Event> queryWrapper) {
        Page<Event> queryPage = eventService.page(pageInfo, queryWrapper);
        List<Event> records = queryPage.getRecords();
        List<JSONObject> jsonObjectList = getEventJsonObjectList(records);
        Page<JSONObject> queryPageDTO = new Page<>();
        BeanUtils.copyProperties(queryPage, queryPageDTO);
        queryPageDTO.setRecords(jsonObjectList);
        PageInfo pageResult = PageInfo.of(queryPageDTO);
        return JsonResult.success(pageResult);
    }

    /**
     * 将模型列表转换为jsonObject 列表
     *
     * @param events 模型列表
     * @return 返回结果
     */
    private List<JSONObject> getEventJsonObjectList(List<Event> events) {
        List<JSONObject> jsonList = new ArrayList<>();
        events.forEach(m -> jsonList.add(m.fetchJsonObject()));
        return jsonList;
    }

    /**
     * 从actionData 取出jsonObject列表 转换成模型列表
     *
     * @param actionData 参数
     * @return 返回模型实体集合
     */
    private List<Event> transformActionDataList(ActionData<JSONObject> actionData) {
        List<JSONObject> jsonObjectList = actionData.getData();
        List<Event> events = new ArrayList<>();
        jsonObjectList.forEach(j -> {
            Event event = new Event(j);
            events.add(event);
        });
        return events;
    }
}
